package com.learn.training.multithread.chapter9.demo2;

import java.util.concurrent.CompletableFuture;

public class Demo {
    public static void main(String[] args) throws InterruptedException {
        System.out.println(System.currentTimeMillis());
        //第一个任务
        CompletableFuture<String> cfQuery = CompletableFuture.supplyAsync(() -> {
            System.out.println(queryCode("中国石油"));
            return queryCode("中国石油");
        });
        System.out.println(System.currentTimeMillis());

        //cfQuery成功后执行第二个任务
        CompletableFuture<Double> cfFetch = cfQuery.thenApplyAsync(Demo::fetchPrice);

        System.out.println(System.currentTimeMillis());
        //cfFetch成功后打印结果
        cfFetch.thenAccept((result) -> {
            System.out.println("Price: " + result);
        });

        //主进程不要立刻结束，否则CompletableFuture默认使用的线程池会立刻关闭:
        Thread.sleep(50000);
    }

    static String queryCode(String name) {
        try {
            Thread.sleep(10000);
            name = name + System.currentTimeMillis();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return name;
    }

    static Double fetchPrice(String code) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return 5 + Math.random() * 20;
    }
}
